package com.magist.manage.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.logging.Logger;

@Component
public class SendEmailUtils {

    private static Logger logger = Logger.getLogger("SendEmailUtils.class");


    private static String user;

    private static String password;

    private static String host;
    private static String protocol;
    private static String auth;
    private static String socketFactory;
    private static String port;




    @Value("${mail.user}")
    public void setUser(String user) {
        SendEmailUtils.user = user;
    }

    @Value("${mail.password}")
    public void setPassword(String password) {
        SendEmailUtils.password = password;
    }

    @Value("${mail.host}")
    public void setHost(String host) {
        SendEmailUtils.host = host;
    }

    @Value("${mail.protocol}")
    public void setProtocol(String protocol) {
        SendEmailUtils.protocol = protocol;
    }
    @Value("${mail.auth}")
    public void setAuth(String auth) {
        SendEmailUtils.auth = auth;
    }
    @Value("${mail.socketFactory}")
    public void setSocketFactory(String socketFactory) {
        SendEmailUtils.socketFactory = socketFactory;
    }
    @Value("${mail.port}")
    public void setPort(String port) {
        SendEmailUtils.port = port;
    }

    public static void sendEmail(String subject, String content, String receiver) {
        try {
            Properties properties = new Properties();
            properties.setProperty("mail.host", host);
            properties.setProperty("mail.transport.protocol", protocol);
            properties.setProperty("mail.smtp.auth", auth);
            properties.setProperty("mail.smtp.socketFactory.class", socketFactory);
            properties.setProperty("mail.smtp.port", port);
            Session session = Session.getDefaultInstance(properties);
            session.setDebug(true);
            Transport transport = session.getTransport();
            transport.connect(host, user, password);
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.addRecipients(Message.RecipientType.TO, receiver);
            mimeMessage.setFrom(new InternetAddress(user));
            mimeMessage.setSubject(subject);
            mimeMessage.setContent(content, "text/html;charset=utf-8");
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            transport.close();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

}